import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import Layout from '@/layout'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: [],
  systom:'',
}

const mutations = {
  SET_SYSTOM: (state, s) => {
    state.systom = s
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {

  systom({ commit }, s) {
    commit('SET_SYSTOM',s)
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
      // login({ username: 373673, password: 123456 }).then(response => {
        // const { data } = response

        commit('SET_TOKEN', response.Result.Token)
        setToken(response.Result.Token)
        resolve()
        // debugger

      }).catch(error => {
        reject(error)
      })
    })
  },
  //2020-12-26 peter
  setSSOUserToken({ commit }, ssouserToken) {
    commit('SET_TOKEN', ssouserToken)
    setToken(ssouserToken)
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          reject('Verification failed, please Login again.')
        }
        const { roles, name, avatar, introduction, menu } = data
        // debugger
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        if (!menu || menu.length <= 0) {
          reject('getInfo: menus must be a non-null array!')
        }

        const menus = GetMenuList(menu, 0)

        // console.log(menus)
        commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)
        commit('SET_MENUS', menus)
        // alert(12)
        // debugger
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }

}

function findMenu(data, parentid) {
  var returnedItem = [] // ����һ��������ֵ�ı���
  var find = function (arr, id) {
    arr.forEach((item) => { // ����foreachѭ������
      if (item.Parentid == id)// �жϵݹ��������
      {
        returnedItem.push(item)
      }
    })
  }
  find(data, parentid)
  return returnedItem
}
function GetMenuList(data, parentid) {
  // debugger
  const returnedItem = [] // ����һ��������ֵ�ı���
  var find = function (arr, id) {
    const menus = []
    arr.forEach((item) => { // ����foreachѭ������
      if (item.Parentid == id)// �жϵݹ��������
      {
        let component = item.Component == 'layout' ? Layout : function component(resolve) {
          require(['@/views/' + item.Component], resolve)
        }
        let childmodel = {
          path: item.Path,
          // component: Layout,
          // component: function component(resolve) {
          //   require(['@/views/' + item.Component], resolve)
          // },
          component: component,
          AppType: item.AppType,
          InterID: item.InterID,
          redirect: item.Redirect,
          alwaysShow: true,
          name: item.Name,
          hidden: item.Hidden,
          meta: { title: item.Title, icon: item.IconUrl }
        }

        var child = []
        var childlist = []
        child = findMenu(data, item.Id)

        if (child.length > 0) // �ж�chlidren�Ƿ�������
        {
          childmodel.children = []

          childlist = find(child, item.Id) // �ݹ����
          if (childlist != null) {
            childmodel.children = childlist
          }
        } else {
          childmodel = {
            path: item.Path,
            // component: () => import('@/views/' + item.component),
            component: function component(resolve) {
              require(['@/views/' + item.Component], resolve)
            },
            hidden: item.Hidden,
            InterID: item.InterID,
            AppType: item.AppType,
            name: item.Name,
            meta: { title: item.Title, icon: item.IconUrl }
          }
        }
        menus.push(childmodel)
      }
    })
    // menus
    // debugger
    return menus
  }
  var menu = null
  returnedItem.push(find(data, parentid))
  console.log(returnedItem)
        // debugger
  
  return returnedItem[0]
}
/**
    * ��̨��ѯ�Ĳ˵�����ƴװ��·�ɸ�ʽ������
    * @param routes
    */
function generaMenu(data) {
  const routerData = []
  data.forEach(item => {
    if (item.ParentId == 0) {
      const menu = [{
        path: '/zip',
        component: Layout,
        redirect: '/zip/download',
        alwaysShow: true,
        name: 'Zip',
        meta: { title: 'Zip', icon: 'zip' },
        children: [{
          path: 'download',
          component: function component(resolve) {
            require(['@/views/zip/index'], resolve)
          },
          name: 'ExportZip',
          meta: { title: 'Export Zip' }
        }]
      }]
      routerData.push(item)
    }
  })

  return routerData
  // data.forEach(item => {
  //    
  //     alert(JSON.stringify(item))
  //    console.log(`@/views/${item.Path}/index`)

  //    const menu = {};
  //    let value = item.Path;
  //    menu.component = function component(resolve) {
  //        require(['@/views/' + value+'/index'], resolve);
  //    };
  //    menu.path = item.Path === '#' ? item.Id + '_key' : item.Path
  //    menu.children = [];
  //    menu.name = 'menu_' + item.Id
  //    menu.meta= { title: item.Name, id: item.Id }

  //    routerData = (menu);
  //    if (item.ParentId == 0) {
  //        global.antRouter.push(routerData);
  //    }
  //    if (item.children) {
  //        generaMenu(routerData.children, item.children)
  //    }
  //    else {
  //        global.antRouter.push(routerData);
  //    }

  // })
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
